package com.example.javaweb1.controller;

import com.example.javaweb1.entity.User;
import com.example.javaweb1.mapper.UserMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/register")
    public String register(User user, Model model) {
        if (user.getUsername()==null||user.getUsername().isEmpty()){
           model.addAttribute("msg","用户名不能为空");
            return "register";
        }
        User existingUser=userMapper.findUserByName(user.getUsername());
        if (existingUser!=null){
            model.addAttribute("mag","用户名已经存在");
            return "register";

        }
        userMapper.insert(user);
        model.addAttribute("msg","注册成功");
            return "redirect:/uplode/4.html";
    }


    @RequestMapping(value = "/login")
    public String login(User user, Model model, HttpServletResponse response, HttpSession session){
        User exitUser=userMapper.findUserByName(user.getUsername());

        if(user.getUsername()==null||user.getUsername().isEmpty()){
           model.addAttribute("msg","用户名不能为空");
            return "login.html";
        }
        if(user.getPassword()==null||user.getPassword().isEmpty()){
            model.addAttribute("msg","密码不能为空");
            return "login.html";
        }
        if(exitUser==null){
            model.addAttribute("msg","该用户未注册");
            return "login.html";
        }
        if(!user.getPassword().equals(exitUser.getPassword())){
           model.addAttribute("msg","用户输入的密码有误");
            return "login.html";
        }else{
            Cookie username=new Cookie("username",user.getUsername());
            username.setMaxAge(60*60*24);
            response.addCookie(username);
          session.setAttribute("loginUser",exitUser.getUsername());
            model.addAttribute("msg","登录成功");

            return "redirect:/uplode/4.html";

        }}}


